package com.wjerp.tplus.server.domain.service.impl;

import com.wjerp.tplus.server.common.constant.ErrorDetail;
import com.wjerp.tplus.server.common.constant.RedisKey;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.model.CaptchaResponse;
import com.wjerp.tplus.server.common.utils.BCage;
import com.wjerp.tplus.server.common.utils.RedisUtils;
import com.wjerp.tplus.server.common.utils.StaticMethods;
import com.wjerp.tplus.server.domain.service.CaptchaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public CaptchaResponse generate() throws BusinessException {

        CaptchaResponse captcha = new CaptchaResponse();

        String text = StaticMethods.generateRandomCaptchaText();
        String token = StaticMethods.generateCaptchaToken();

        BCage cage = new BCage();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            cage.draw(text, out);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorDetail.FAIL_TO_GET_CAPTCHA);
        }
        captcha.setImage(out.toByteArray());
        captcha.setMime("image/jpeg");
        captcha.setToken(token);

        ///captchaDAO.create(token, text);
        Map<String,Object> captchaMap=new HashMap<>();
        captchaMap.put("token",token);
        captchaMap.put("value",text);
        System.out.println("验证码："+captchaMap);
        redisUtils.set(RedisKey.CAPTCHA+token,captchaMap,5*60L);
        return captcha;
    }

    @Override
    public boolean matches(String token, String text) throws BusinessException {
        Object captchaObj=redisUtils.get(RedisKey.CAPTCHA+token);
        if(captchaObj==null){
                throw new BusinessException(ErrorDetail.CAPTCHA_NOT_MATCHED);
        }else{
            Map<String,Object> captchaMap= (Map<String, Object>) captchaObj;
            if(captchaMap.get("token").toString().equalsIgnoreCase(token)
                    && captchaMap.get("value").toString().equalsIgnoreCase(text)){
                return true;
            }
            throw new BusinessException(ErrorDetail.CAPTCHA_NOT_MATCHED);
        }
    }

    @Override
    public String getCaptchaText(String token) {
        Map<String,Object> captchaMap = (Map<String, Object>) redisUtils.get(RedisKey.CAPTCHA+token);
        return captchaMap.get("value").toString();
    }
}
